#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
登录处理模块
负责处理网站登录相关操作
"""

import time
import traceback
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException

class LoginHandler:
    """登录处理类，处理网站登录相关操作"""
    
    def __init__(self, driver, config):
        """初始化登录处理器
        
        Args:
            driver: WebDriver对象
            config: 包含登录配置的字典
        """
        self.driver = driver
        self.config = config
        self.login_url = "https://www.hifini.com/user-login.htm"
    
    def login(self):
        """执行登录流程"""
        # 打开登录页面
        print(f"\n正在打开登录页面: {self.login_url}")
        self.driver.get(self.login_url)
        
        # 使用配置文件中的用户名和密码
        username = self.config['username']
        password = self.config['password']
        
        if not username or not password:
            print("\n提示: 未在配置文件中找到有效的用户名或密码")
            print("请手动完成登录过程，或编辑config.ini文件设置您的账号密码")
            input("\n请手动完成登录，然后按回车键继续...")
            return
        
        try:
            # 等待页面加载
            wait = WebDriverWait(self.driver, 10)
            
            # 打印页面信息以便调试
            print("页面标题: {}".format(self.driver.title))
            print("当前页面URL: {}".format(self.driver.current_url))
            
            # 查找并填写用户名
            username_input = self._find_username_field()
            if username_input:
                username_input.clear()
                username_input.send_keys(username)
                print("已自动填写用户名")
            else:
                print("无法找到用户名输入框")
                raise Exception("找不到用户名输入框")
            
            # 查找并填写密码
            password_input = self._find_password_field()
            if password_input:
                password_input.clear()
                password_input.send_keys(password)
                print("已自动填写密码")
            else:
                print("无法找到密码输入框")
                raise Exception("找不到密码输入框")
            
            # 查找并点击登录按钮
            login_button = self._find_login_button()
            if login_button:
                login_button.click()
                print("已自动点击登录按钮")
            else:
                print("无法找到登录按钮")
                raise Exception("找不到登录按钮")
            
            # 等待用户完成验证码验证
            print("\n请按以下步骤操作:")
            print("1. 请完成验证码/人工验证操作(如有)")
            print("2. 验证完成后，按回车键继续执行脚本")
            
            input("\n请完成验证操作，然后按回车键继续...")
            print("验证完成，继续执行自动化任务...")
            
        except Exception as e:
            print(f"自动填写登录信息失败: {str(e)}")
            print("可能原因:")
            print("1. 网页结构已更改，找不到输入框或登录按钮")
            print("2. 网络连接问题")
            print("3. 页面加载超时")
            
            print("\n请按以下步骤操作:")
            print("1. 请手动完成登录和验证码操作")
            print("2. 登录成功后，按回车键继续执行脚本")
            
            # 等待用户完成登录
            input("\n请完成登录，然后按回车键继续...")
    
    def _find_username_field(self):
        """查找用户名输入框
        
        Returns:
            WebElement: 用户名输入框元素，未找到时返回None
        """
        # 尝试多种可能的选择器
        selectors = [
            (By.NAME, "email"),
            (By.ID, "email"),
            (By.NAME, "username"),
            (By.ID, "username"),
            (By.CSS_SELECTOR, "input[type='email']"),
            (By.CSS_SELECTOR, "input[type='text']"),
            (By.XPATH, "//input[contains(@placeholder, '用户名') or contains(@placeholder, '邮箱')]")
        ]
        
        for selector_type, selector_value in selectors:
            try:
                field = self.driver.find_element(selector_type, selector_value)
                print(f"找到用户名输入框: {selector_type} - {selector_value}")
                return field
            except NoSuchElementException:
                continue
        
        return None
    
    def _find_password_field(self):
        """查找密码输入框
        
        Returns:
            WebElement: 密码输入框元素，未找到时返回None
        """
        # 尝试多种可能的选择器
        selectors = [
            (By.NAME, "password"),
            (By.ID, "password"),
            (By.CSS_SELECTOR, "input[type='password']"),
            (By.XPATH, "//input[contains(@placeholder, '密码')]")
        ]
        
        for selector_type, selector_value in selectors:
            try:
                field = self.driver.find_element(selector_type, selector_value)
                print(f"找到密码输入框: {selector_type} - {selector_value}")
                return field
            except NoSuchElementException:
                continue
        
        return None
    
    def _find_login_button(self):
        """查找登录按钮
        
        Returns:
            WebElement: 登录按钮元素，未找到时返回None
        """
        # 尝试多种可能的选择器
        selectors = [
            (By.NAME, "submit"),
            (By.ID, "submit"),
            (By.CSS_SELECTOR, "button[type='submit']"),
            (By.XPATH, "//button[contains(text(), '登录')]"),
            (By.XPATH, "//input[@type='submit']"),
            (By.XPATH, "//button[@type='submit']")
        ]
        
        for selector_type, selector_value in selectors:
            try:
                button = self.driver.find_element(selector_type, selector_value)
                print(f"找到登录按钮: {selector_type} - {selector_value}")
                return button
            except NoSuchElementException:
                continue
        
        return None 